import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
//        +----------+-------------+------+-----+---------+----------------+
//        | Field    | Type        | Null | Key | Default | Extra          |
//        +----------+-------------+------+-----+---------+----------------+
//        | userId   | int(11)     | NO   | PRI | NULL    | auto_increment |
//        | username | varchar(50) | YES  | UNI | NULL    |                |
//        | password | varchar(50) | YES  |     | NULL    |                |
//        | github   | text        | YES  |     | NULL    |                |
//        +----------+-------------+------+-----+---------+----------------+
//用户数据库操作封装
public class UserDao {

    //通过userId查询用户
    public User selectById(int userId) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //1.建立连接
            connection = DBUtil.getConnection();

            //2.构造sql语句
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);

            //3.执行sql语句
            resultSet =statement.executeQuery();
            if(resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setGithub(resultSet.getString("github"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }


    //通过username查询对应用户
    public User selectByName(String username) {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            //1.建立连接
            connection = DBUtil.getConnection();

            //2.构造sql语句
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,username);

            //3.执行sql语句
            resultSet =statement.executeQuery();
            if(resultSet.next()) {
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                user.setGithub(resultSet.getString("github"));
                return user;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }

    //3.获取博客数量
}
